package com.sctvcloud.qingchuan.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.ruihang.generalibrary.ui.widget.CustomFontEditText;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.qingchuan.R;
import com.sctvcloud.qingchuan.application.Constances;
import com.sctvcloud.qingchuan.beans.PoliticsAccountBean;
import com.sctvcloud.qingchuan.http.AbsNetCallBack;
import com.sctvcloud.qingchuan.http.NetUtils;
import com.sctvcloud.qingchuan.ui.activities.PoliticsChooseObjActivity;
import com.sctvcloud.qingchuan.ui.adapter.PoliticsAccountAdapter;
import com.sctvcloud.qingchuan.ui.adapter.holder.PoliticsAccountHolder;
import com.sctvcloud.qingchuan.ui.utils.DataUtils;
import com.sctvcloud.qingchuan.utils.ListTypeUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;

/**
 * 各融媒号Tag下的问政对象列表
 */
public class PoliticsAccountFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener, PoliticsAccountHolder.OnPoliticsAccountClickListener {

    @BindView(R.id.input_key)
    protected CustomFontEditText searchInput;
    @BindView(R.id.fm_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView recyclerView;
    private PoliticsAccountAdapter adapter;
    private long tagId = 0;
    private List<PoliticsAccountBean> dataList = new ArrayList<>();
    private PoliticsChooseObjActivity parentActivity;


    public PoliticsAccountFragment() {
        // Required empty public constructor
    }

    public void setTagId(String id) {
        if (!TextUtils.isEmpty(id)) {
            this.tagId = Long.parseLong(id);
        }
    }

    public void setParentActivity(PoliticsChooseObjActivity parentActivity) {
        this.parentActivity = parentActivity;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_politics_account, container, false);
        ButterKnife.bind(this, view);
        return view;
    }


    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        adapter = new PoliticsAccountAdapter(getContext(), null, this);
        recyclerView.setAdapter(adapter);
        searchInput.setOnEditorActionListener(new EditText.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    ((InputMethodManager) searchInput.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(searchInput.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    //获取编辑框内容,执行相应操作
                    String key = searchInput.getText().toString().trim();
                    dataList.clear();
                    getData(tagId, key);
                    return true;
                }
                return false;
            }
        });
        recyclerView.setFocusable(true);
        recyclerView.setFocusableInTouchMode(true);
        recyclerView.requestFocus();
        refreshLayout.autoRefresh();
    }


    @Override
    public void onPause() {
        super.onPause();

    }

    @Override
    public void onRefresh() {
        dataList.clear();
        getData(tagId, "");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (ListUtils.isListValued(dataList)) {
            refreshSelectedAccount(getSelectedAuthorId());
        }
    }
//
//    @Override
//    public void setUserVisibleHint(boolean isVisibleToUser) {
//        super.setUserVisibleHint(isVisibleToUser);
////        if (getUserVisibleHint()) {
//        //界面可见
//        if (ListUtils.isListValued(dataList)) {
//            refreshSelectedAccount(lastAuthorId);
//        }
////        }
//    }

    /**
     * 获取数据
     */
    private void getData(long tagId, String key) {
        Map<String, Object> formMaildata = new HashMap<>();
        formMaildata.put("tagId", tagId);
        if (!TextUtils.isEmpty(key)) {
            formMaildata.put("userNameByLike", key);
        }
        RequestBody body = DataUtils.toRequestBody(formMaildata);
        NetUtils.getNetAdapter().toGetPoliticsAccount(getOwnerName(), Constances.TENANT_ID, body, new AbsNetCallBack<String>(String.class) {
            @Override
            public void onSucStr(String news) {
                if (!TextUtils.isEmpty(news)) {
                    try {
                        List<PoliticsAccountBean> list = gson.fromJson(news, ListTypeUtils.PoliticsAccountBean());
                        if (ListUtils.isListValued(list)) {
                            dataList.addAll(list);
                            refreshSelectedAccount(getSelectedAuthorId());
                            adapter.setData(dataList);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    onError(null, "数据异常");
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                toast(errorMsg);

            }


            @Override
            public void onEnd() {
                onNetFinish();
            }
        });


    }

    private void onNetFinish() {
        refreshLayout.refreshComplete();
    }

    @Override
    public void OnAccountClick(PoliticsAccountBean account) {
        if (parentActivity != null) {
            parentActivity.setPoliticsObj(account);
        }
        refreshSelectedAccount(account.getAuthorId());
        adapter.setData(dataList);
    }

    /**
     * 刷新上次选中的问政对象
     *
     * @param authorId
     */
    public void refreshSelectedAccount(long authorId) {
        if (ListUtils.isListValued(dataList)) {
            for (int i = 0; i < dataList.size(); i++) {
                if (dataList.get(i).getAuthorId() != authorId) {
                    dataList.get(i).setSelected(false);
                } else {
                    dataList.get(i).setSelected(true);
                }
            }
        }
    }

    private long getSelectedAuthorId() {
        if (null != parentActivity.getPoliticsObj()) {
            return parentActivity.getPoliticsObj().getAuthorId();
        } else {
            return 0;
        }
    }

}
